package com.base.controller.czb.czbapi;

import com.base.controller.utils.CZB.CZBTokenUtils;
import com.base.po.param.NetState;
import com.base.po.voip.Subscribers;
import com.base.po.voip.Users;
import com.base.service.SubscribersService;
import com.base.service.UsersService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/token")
public class TokenController {
    @Autowired
    UsersService usersService;
    @Autowired
    SubscribersService subscribersService;

    @RequestMapping(value = "/getCZBToken", method = {RequestMethod.POST, RequestMethod.GET})
    public @ResponseBody
    NetState gettoken(HttpServletRequest request, String parentId, String mobile){
        NetState netState=new NetState();
        if (parentId==null || parentId.equals("")||mobile==null ||mobile.equals("")){
            netState.setErrorCode(NetState.PARAMS_ERROR);
            netState.setData("请填写参数！");
            return netState;
        }
        Users users=usersService.selectByPrimaryKey(parentId);
        List<Subscribers> subscribersList=subscribersService.selectBySub(mobile,parentId);
        if (users ==null || subscribersList.size()<=0){
            netState.setErrorCode(NetState.PARAMS_ERROR);
            netState.setData("参数异常");
            return netState;
        }
        Subscribers sub=subscribersList.get(0);
        Long timeStamp = new Date().getTime();
        try{
            String token= CZBTokenUtils.createToken(timeStamp,sub.getMobile());
            netState.setJson(JSONObject.fromObject(token));
            netState.setErrorCode(NetState.SUCCESS_CONN);
        }catch (Exception e){
            e.printStackTrace();
            netState.setData("调用接口发生错误");
            netState.setErrorCode(NetState.FEAILED);
        }
        return netState;
    }
}
